package com.romotc.qqrobot.webqq.qqInterfaceCatching;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;

import com.romotc.json.tools.Jackson;
import com.romotc.qqrobot.bean.PollResult;
import com.romotc.qqrobot.bean.PollResultService;
import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.bean.SendMsg;
import com.romotc.qqrobot.bean.SendMsgService;
import com.romotc.qqrobot.webqq.WebQQConstant;
import com.romotc.qqrobot.webqq.bean.Poll2_ResponseBody;
import com.romotc.qqrobot.webqq.bean.Poll2_ResponseBody_Result;
import com.romotc.scache.RequestSpy;
import com.romotc.scache.WebConnection;
/**
 * 客服虚拟工号poll拦截器
 * @author Administrator
 *
 */
public class Poll2_CustServiceHold_Catching extends QQUrlBodyCatching {

	@Override
	public boolean modifyResponse(WebConnection wc, RequestSpy rqSpy)
			throws IOException {
		return false;
		
	}

	@Override
	String getHackReqBodyStr(RequestSpy requestSpy, Map<String, Object> var) {
		String loginUserName = requestSpy.getReqCookiesJson().optString(WebQQConstant.Cookie_ptui_loginuin);
		QQLogedin curQQ = QQLogedin.getCurQqLogedIn(requestSpy);
		if(WebQQConstant.isRobotUin(loginUserName) && curQQ != null) {
			
			//每5秒钟检查一下数据库中有没有给自己的消息
			//最多检查12次 (一分钟）)
			int count = 20;
			try {
				//消息列表
				List<PollResult> msgList = null;
				while(count-- > 0) {
					//根据客服工号查询消息列表
					msgList = PollResultService.qryPolls2CustService(curQQ.getCsId());
					
					if(msgList == null || msgList.isEmpty()) {
						//休眠没有查到消息则休眠5s秒
						Thread.sleep(3 * 1000);
					}else {
						//将PollResult
						return sendPoll2CustService(msgList,curQQ);
					}
				}
				
				return "{\"retcode\":102,\"errmsg\":\"\"}";
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 将消息转换成字符串转发给客服人员 修改状态为已转发
	 * 转发的时候fromUin 为-的客户id
	 *         toUin 为客服人员id
	 *         msgId
	 *         msgid2
	 *         time
	 * @param msgList
	 * @return
	 */
	private String sendPoll2CustService(List<PollResult> msgList,QQLogedin curQQ) {
//		if(true)
//			return "{\"retcode\":0,\"result\":[{\"poll_type\":\"message\",\"value\":{\"msg_id\":891,\"from_uin\":-309,\"to_uin\":2,\"msg_id2\":852580,\"msg_type\":9,\"reply_ip\":176722899,\"time\":1328484781,\"content\":[[\"font\",{\"size\":13,\"color\":\"000000\",\"style\":[0,0,0],\"name\":\"\u9ED1\u4F53\"}],\"dd \"]}},{\"poll_type\":\"message\",\"value\":{\"msg_id\":891,\"from_uin\":-309,\"to_uin\":2,\"msg_id2\":852580,\"msg_type\":9,\"reply_ip\":176722899,\"time\":1328484781,\"content\":[[\"font\",{\"size\":13,\"color\":\"000000\",\"style\":[0,0,0],\"name\":\"\u9ED1\u4F53\"}],\"dd \"]}}]}";
		Poll2_ResponseBody pollBody = new Poll2_ResponseBody();
		List<Poll2_ResponseBody_Result> results = new ArrayList<Poll2_ResponseBody_Result>(msgList.size());
		Poll2_ResponseBody_Result pollResult;
		int i = 0;
		for(PollResult pollObj : msgList) {
			pollResult = new Poll2_ResponseBody_Result(pollObj);
			pollResult.getValue().setTime(pollObj.getTime());
			pollResult.getValue().setTo_uin(pollObj.getCustServiceId());
			pollResult.getValue().setFrom_uin(-pollObj.getCustId());
			pollResult.getValue().setMsg_id(curQQ.getReciveMsg_id());
			pollResult.getValue().setMsg_id2(pollResult.getValue().getMsg_id2());
			results.add(pollResult);
		}
		
		pollBody.setResult(results);
		try {
			String jsonString = Jackson.getObjectMaper().writeValueAsString(pollBody);
			//jsonString = "{\"retcode\":0,\"result\":[{\"poll_type\":\"message\",\"value\":{\"msg_id\":16006,\"from_uin\":-26,\"to_uin\":2,\"msg_id2\":578422,\"msg_type\":9,\"reply_ip\":176498388,\"time\":1329017141,\"content\":[[\"font\",{\"size\":13,\"color\":\"000000\",\"style\":[0,0,0],\"name\":\"\u9ED1\u4F53\"}],\"9\u70B9 \"]}}]}";
			//修改状态
			for(PollResult pollObj : msgList) {
				pollObj.Delete();
				pollObj.setMsgStatus(pollObj.Status_Forwarded);
				pollObj.Save();
			}
			
			return jsonString;
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "{\"retcode\":102,\"errmsg\":\"\"}";
	}

	@Override
	ArrayList<String> hackRequestHeader(RequestSpy requestSpy, int bodySize,
			Map<String, Object> var) {
		ArrayList<String > headers = new ArrayList<String>();
		headers.add("Cache-Control:no-cache");
		headers.add("Connection:Keep-Alive");
		headers.add("Content-Length:" + bodySize);
		headers.add("Content-Type:text/plain; charset=utf-8");
		headers.add("Date:Thu, 26 Jan 2012 09:41:33 GMT");
		headers.add("Proxy-Connection:Keep-Alive");
		/**
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:29
Content-Type:text/plain; charset=utf-8
Date:Thu, 26 Jan 2012 09:41:33 GMT
Proxy-Connection:Keep-Alive
		 */
		return null;
	}

	@Override
	boolean isGoOn(RequestSpy requestSpy) {
		// TODO Auto-generated method stub
		return false;
	}

}
